package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.probox.common.core.constant.CachePrefix;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.entity.domain.customer.CustomerGroup;
import com.probox.common.entity.domain.customer.CustomerGroupdefinitionInfo;
import com.probox.common.entity.mapper.customer.*;
import com.probox.common.redis.service.RedisService;
import com.probox.customer.api.domain.CustomerInfoVo;
import com.probox.common.entity.service.customer.ICustomerGroupDefinitionService;
import com.probox.common.entity.service.customer.ICustomerOperationService;
import com.probox.common.entity.service.customer.ICustomerGroupService;
import com.probox.common.entity.vo.customer.CustomerGroupVo;
import com.probox.common.entity.vo.customer.CustomerGroupdefinitionInfoVo;
import com.probox.common.entity.vo.customer.GroupDefinitionInfoQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 客户分群Service业务层处理
 *
 * @author zsy
 * @date 2021-07-15
 */
@Service
@Transactional
public class CustomerGroupServiceImpl extends ServiceImpl<CustomerGroupMapper, CustomerGroup> implements ICustomerGroupService {
    @Autowired
    private CustomerGroupMapper customerGroupMapper;

    @Autowired
    private CustomerGroupDefinitionMapper customerGroupDefinitionMapper;

    @Autowired
    private CustomerGroupdefinitionInfoMapper customerGroupdefinitionInfoMapper;

    @Autowired
    private ICustomerGroupDefinitionService customerGroupDefinitionService;

    @Autowired
    private ICustomerOperationService customerOperationService;

    @Autowired
    private CustomerOperationMapper customerOperationMapper;

    @Autowired
    private CustomerOperationPrivilegeMapper customerOperationPrivilegeMapper;

    @Autowired
    private CustomerOperationPrivilegeGiveMapper customerOperationPrivilegeGiveMapper;

    @Autowired
    private CustomerInfoMapper customerInfoMapper;


    @Autowired
    RedisService redisService;

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    //客户人群信息key
    private String key  = CachePrefix.CUSTOMER_GROUP;

    //客户人群信息过期时间
    private Long expires = 1L;

    /**
     * 查询客户分群列表
     *
     * @return 客户分群
     */
    @Override
    public List<CustomerGroup> queryList() {
        QueryWrapper<CustomerGroup> queryWrapper = Wrappers.query();
        queryWrapper.eq("PLATFORM_ID", SecurityUtils.getPlatformId());
        queryWrapper.eq("DATA_STATUS", DataStatus.valid.getKey());
        queryWrapper.select("GROUP_UID","GROUP_NAME","GROUP_DESC");
        return customerGroupMapper.selectList(queryWrapper);
    }

    /**
     * 新增客户分群
     *
     * @param customerGroup 客户分群
     * @return 结果
     */
    @Override
    public boolean insertCustomerGroup(CustomerGroup customerGroup) {

        return this.save(customerGroup);

    }

    /**
     * 修改客户分群
     *
     * @param customerGroup 客户分群
     * @return 结果
     */
    @Override
    public boolean updateCustomerGroup(CustomerGroup customerGroup) {

        return this.updateById(customerGroup);
    }

    /**
     * 批量删除客户分群
     *
     * @param groupUids 需要删除的客户分群ID
     * @return 结果
     */
    @Override
    public boolean deleteCustomerGroupByIds(Long[] groupUids) {
        redisService.deleteObject(key+SecurityUtils.getPlatformId());
        return this.removeByIds(Arrays.asList(groupUids));
    }


    /**
     * 查询全部客户人群信息
     * @param customerGroupvo
     * @return
     */
    @Override
    public List<CustomerGroupVo> selectGroupInfo(CustomerGroupVo customerGroupvo) {
        List<CustomerGroupVo>  customerGroupVoList = redisService.getCacheList(key+SecurityUtils.getPlatformId());
        if (ObjectUtil.isEmpty(customerGroupVoList)){
            customerGroupvo.setPlatformId(SecurityUtils.getPlatformId());
            customerGroupVoList = customerGroupMapper.selectGroupDefinitionInfo(customerGroupvo);
            //更新人群数量
            for (CustomerGroupVo groupVo:customerGroupVoList){
                List<GroupDefinitionInfoQuery> groupDefinitionInfoQuerie = new ArrayList<>();
                List<CustomerGroupdefinitionInfoVo> customerGroupdefinitionInfoVos = groupVo.getCustomerGroupdefinitionInfoVos();
                for (CustomerGroupdefinitionInfoVo groupdefinitionInfoVo:customerGroupdefinitionInfoVos){
                    GroupDefinitionInfoQuery infoQuery = new GroupDefinitionInfoQuery();
                    infoQuery.setDefinitionSectionvalue(groupdefinitionInfoVo.getDefinitionSectionvalue());
                    infoQuery.setDefinitionUid(groupdefinitionInfoVo.getDefinitionUid());
                    infoQuery.setDefinitionValue(groupdefinitionInfoVo.getDefinitionValue());
                    infoQuery.setDefinitionUnitvalue(groupdefinitionInfoVo.getDefinitionUnitvalue());
                    groupDefinitionInfoQuerie.add(infoQuery);
                }
                List list = customerGroupDefinitionService.selectConditionCustomerInfo(groupDefinitionInfoQuerie);
                if (list!=null){
                    groupVo.setGroupNumber(Long.parseLong(String.valueOf(list.size())));
                    CustomerGroup customerGroup = customerGroupMapper.selectById(groupVo.getGroupUid());
                    customerGroup.setGroupNumber(Long.parseLong(String.valueOf(list.size())));
                    customerGroupMapper.updateById(customerGroup);
                }
            }
            if(customerGroupVoList.size() > 0){
                redisService.setCacheList(key+SecurityUtils.getPlatformId(),customerGroupVoList);
                redisService.expire(key+SecurityUtils.getPlatformId(),expires,TimeUnit.DAYS);
            }
        }
        return customerGroupVoList;

    }

    /**
     * 新增人群分组
     * @param customerGroupVo
     * @return
     */
    @Override
    public boolean addGroup(CustomerGroupVo customerGroupVo) {
        DateTime date = DateUtil.date();
        Long platformId = SecurityUtils.getPlatformId();
        String username = SecurityUtils.getUsername();
        Long userId = SecurityUtils.getUserId();
        //人群信息
        CustomerGroup group = new CustomerGroup();
        group.setPlatformId(platformId);
        group.setGroupName(customerGroupVo.getGroupName());
        group.setGroupNumber(customerGroupVo.getGroupNumber());
        group.setGroupDesc(customerGroupVo.getGroupDesc());
        group.setCreateUser(userId);
        group.setCreateName(username);
        group.setCreateTime(date);
        group.setDataStatus(DataStatus.valid.getKey());
        customerGroupMapper.insert(group);
        //人群特征信息
        List<CustomerGroupdefinitionInfoVo> customerGroupdefinitionInfoVos = customerGroupVo.getCustomerGroupdefinitionInfoVos();
        for (CustomerGroupdefinitionInfoVo groupdefinitionInfoVo:customerGroupdefinitionInfoVos){
            CustomerGroupdefinitionInfo definitionInfo = new CustomerGroupdefinitionInfo();
            definitionInfo.setPlatformId(platformId);
            definitionInfo.setDefinitionUid(groupdefinitionInfoVo.getDefinitionUid());
            definitionInfo.setGroupUid(group.getGroupUid());
            definitionInfo.setDefinitionStatus("1");
            definitionInfo.setCreateUser(userId);
            definitionInfo.setCreateName(username);
            definitionInfo.setCreateTime(date);
            definitionInfo.setDataStatus(DataStatus.valid.getKey());
            definitionInfo.setDefinitionValue(groupdefinitionInfoVo.getDefinitionValue());
            definitionInfo.setDefinitionSectionvalue(groupdefinitionInfoVo.getDefinitionSectionvalue());
            definitionInfo.setDefinitionUnitvalue(groupdefinitionInfoVo.getDefinitionUnitvalue());
            customerGroupdefinitionInfoMapper.insert(definitionInfo);
        }
        redisService.deleteObject(key+SecurityUtils.getPlatformId());
        return true;
    }

    @Override
    public boolean editGroup(CustomerGroupVo customerGroupVo) {
        DateTime date = DateUtil.date();
        Long platformId = SecurityUtils.getPlatformId();
        String username = SecurityUtils.getUsername();
        Long userId = SecurityUtils.getUserId();
        //人群信息
        CustomerGroup group = customerGroupMapper.selectById(customerGroupVo.getGroupUid());
        group.setPlatformId(platformId);
        group.setGroupName(customerGroupVo.getGroupName());
        group.setGroupNumber(customerGroupVo.getGroupNumber());
        group.setGroupDesc(customerGroupVo.getGroupDesc());
        group.setUpdateTime(date);
        group.setUpdateName(username);
        group.setUpdateUser(userId);
        customerGroupMapper.updateById(group);
        //人群特征信息
        List<CustomerGroupdefinitionInfoVo> customerGroupdefinitionInfoVos = customerGroupVo.getCustomerGroupdefinitionInfoVos();
        ArrayList<String> definitionUIdList=new ArrayList<String>();
        for (CustomerGroupdefinitionInfoVo groupdefinitionInfoVo:customerGroupdefinitionInfoVos){
            QueryWrapper<CustomerGroupdefinitionInfo> groupdefinitionInfoQueryWrapper = new QueryWrapper<>();
            groupdefinitionInfoQueryWrapper.eq("GROUP_UID",group.getGroupUid());
            groupdefinitionInfoQueryWrapper.eq("DEFINITION_UID",groupdefinitionInfoVo.getDefinitionUid());
            groupdefinitionInfoQueryWrapper.eq("DATA_STATUS",DataStatus.valid.getKey());
            CustomerGroupdefinitionInfo customerGroupdefinitionInfo = customerGroupdefinitionInfoMapper.selectOne(groupdefinitionInfoQueryWrapper);
            if (customerGroupdefinitionInfo!=null){
                //修改
                customerGroupdefinitionInfo.setPlatformId(platformId);
                customerGroupdefinitionInfo.setDefinitionValue(groupdefinitionInfoVo.getDefinitionValue());
                customerGroupdefinitionInfo.setDefinitionSectionvalue(groupdefinitionInfoVo.getDefinitionSectionvalue());
                customerGroupdefinitionInfo.setDefinitionUnitvalue(groupdefinitionInfoVo.getDefinitionUnitvalue());

                customerGroupdefinitionInfoMapper.updateById(customerGroupdefinitionInfo);
                if (customerGroupdefinitionInfo!=null){
                    definitionUIdList.add(String.valueOf(customerGroupdefinitionInfo.getCustomerGroupdefinitionUid()));
                }
            }else {
                CustomerGroupdefinitionInfo definitionInfo = new CustomerGroupdefinitionInfo();
                definitionInfo.setPlatformId(platformId);
                definitionInfo.setDefinitionUid(groupdefinitionInfoVo.getDefinitionUid());
                definitionInfo.setGroupUid(group.getGroupUid());
                definitionInfo.setDefinitionStatus("1");
                definitionInfo.setCreateUser(userId);
                definitionInfo.setCreateName(username);
                definitionInfo.setCreateTime(date);
                definitionInfo.setDataStatus(DataStatus.valid.getKey());
                definitionInfo.setDefinitionValue(groupdefinitionInfoVo.getDefinitionValue());
                definitionInfo.setDefinitionSectionvalue(groupdefinitionInfoVo.getDefinitionSectionvalue());
                definitionInfo.setDefinitionUnitvalue(groupdefinitionInfoVo.getDefinitionUnitvalue());
                customerGroupdefinitionInfoMapper.insert(definitionInfo);
            }

        }
        //判断不同则设置无效
        QueryWrapper<CustomerGroupdefinitionInfo> groupdefinitionInfoQueryWrapper = new QueryWrapper<>();
        groupdefinitionInfoQueryWrapper.eq("GROUP_UID",customerGroupVo.getGroupUid());
        groupdefinitionInfoQueryWrapper.eq("DATA_STATUS",DataStatus.valid.getKey());
        groupdefinitionInfoQueryWrapper.select("CUSTOMER_GROUPDEFINITION_UID");
        List<CustomerGroupdefinitionInfo> customerGroupdefinitionInfos = customerGroupdefinitionInfoMapper.selectList(groupdefinitionInfoQueryWrapper);
        String[] definitionUId = new String[customerGroupdefinitionInfos.size()];
        for (int i = 0; i < customerGroupdefinitionInfos.size(); i++) {
            definitionUId[i] = String.valueOf(customerGroupdefinitionInfos.get(i).getCustomerGroupdefinitionUid());
        }
        String[] newDefinitionUId = new String[customerGroupdefinitionInfoVos.size()];
        definitionUIdList.toArray(newDefinitionUId);
        List<String> CustomerGroupdefinitionUidList =  compare(definitionUId,newDefinitionUId);
        for (String uid:CustomerGroupdefinitionUidList){
            if (uid!=null){
                CustomerGroupdefinitionInfo customerGroupdefinitionInfo = customerGroupdefinitionInfoMapper.selectById(uid);
                customerGroupdefinitionInfo.setDataStatus(DataStatus.invalid.getKey());
                customerGroupdefinitionInfoMapper.updateById(customerGroupdefinitionInfo);
            }
        }
        redisService.deleteObject(key+SecurityUtils.getPlatformId());
        return true;
    }

    @Override
    public List<CustomerInfoVo> getGroupCustomerCount(Long groupId) {
        CustomerGroupVo customerGroupVo = customerGroupMapper.selectByIDGroupInfo(groupId);
        List<GroupDefinitionInfoQuery> groupDefinitionInfoQuerie = new ArrayList<>();
        List<CustomerGroupdefinitionInfoVo> customerGroupdefinitionInfoVos = customerGroupVo.getCustomerGroupdefinitionInfoVos();
        for (CustomerGroupdefinitionInfoVo groupdefinitionInfoVo:customerGroupdefinitionInfoVos){
            GroupDefinitionInfoQuery infoQuery = new GroupDefinitionInfoQuery();
            infoQuery.setDefinitionSectionvalue(groupdefinitionInfoVo.getDefinitionSectionvalue());
            infoQuery.setDefinitionUid(groupdefinitionInfoVo.getDefinitionUid());
            infoQuery.setDefinitionValue(groupdefinitionInfoVo.getDefinitionValue());
            infoQuery.setDefinitionUnitvalue(groupdefinitionInfoVo.getDefinitionUnitvalue());
            groupDefinitionInfoQuerie.add(infoQuery);
        }
        List list = customerGroupDefinitionService.selectConditionCustomerInfoByPlatformId(groupDefinitionInfoQuerie,customerGroupVo.getPlatformId());
        if (list.size() >0){
            List<CustomerInfoVo> customerInfoVos = customerInfoMapper.selectCustomerInfo(list);
            return customerInfoVos;
        }
        return null;
    }


    /**
     * 查看指定分群名称及人数
     * @param groupUid
     * @return
     */
    @Override
    public CustomerGroup getGroupInfoById(Long groupUid) {
        CustomerGroup customerGroup = customerGroupMapper.selectById(groupUid);
        return customerGroup;
    }


    /**
     * 查询客户分群
     *
     * @param groupUid 客户分群ID
     * @return 客户分群
     */
    @Override
    public CustomerGroupVo selectCustomerGroupById(Long groupUid) {
        Long PlatformUid = SecurityUtils.getPlatformId();
        CustomerGroupVo customerGroupVo = customerGroupMapper.selectByIDGroupInfo(groupUid);
        return customerGroupVo;
    }


    /**
     * 判断传入的两个数组有哪些值不同
     * @param t1
     * @param t2
     * @param <T>
     * @return
     */
    public static <T> List<T> compare(T[] t1, T[] t2) {
        List<T> list1 = Arrays.asList(t1);
        List<T> list2 = new ArrayList<T>();
        for (T t : t2) {
            if (!list1.contains(t)) {
                list2.add(t);
            }
        }
        if (t2.length==0){
            for (int i = 0; i < t1.length; i++) {
                list2.add(t1[i]);
            }
        }
        return list2;
    }

}
